
'use strict';

const BaseService = require("./base");


class LikeArticleService extends BaseService{
    async likeArticleListByUser(body){
        const {Op} = this.app.Sequelize
        const {user_id} = body
        const likeArticles = this.app.model.LikeArticle.findAll({
            where:{
                user_id,
                [Op.and]:{status:1}
            }
        })
        return likeArticles
    }

    async changeLikeArticleStatus(body){
        const params = this.app._.cloneDeep(body)
        const {literal} = this.app.Sequelize
        // status 1-点赞  0-取消点赞
        const {user_id, article_id,status} = params
        const curLikeArticle = await this.app.model.LikeArticle.findOne({
            where:{
                user_id,article_id
            }
        })
        const addOrReduce = status?'like_count + 1':'like_count - 1'
        if(curLikeArticle){
            const {id} = curLikeArticle
            await this.app.model.LikeArticle.update({status},{
                where:{
                    id
                }
            })
            await this.app.model.Article.update({like_count:literal(addOrReduce)},{
                where:{id:article_id}
            })
        }else{
            params.create_time = new Date()
            await this.app.model.LikeArticle.create(params)
            await this.app.model.Article.update({like_count:literal(addOrReduce)},{
                where:{id:article_id}
            })
        } 
    } 
}


module.exports = LikeArticleService;